<template>
  <div class="customer-page-container">
    <!-- 搜索表单区域 -->
    <div class="search-form">
      <!-- 将 :model 指向 pageObj.page.priceRule -->
      <el-form :inline="true" :model="pageObj.page.priceRule" label-width="90px">
        <el-form-item label="城市代码">
          <!-- v-model 绑定到 pageObj.page.priceRule.cityCode -->
          <el-input v-model="pageObj.page.priceRule.cityCode" placeholder="输入城市代码搜索" clearable />
        </el-form-item>
        <el-form-item label="车辆类型">
          <!-- v-model 绑定到 pageObj.page.priceRule.vehicleType -->
          <el-input v-model="pageObj.page.priceRule.vehicleType" placeholder="输入车辆类型搜索" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="findData(1)">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="showDialog()">新 增</el-button>
      <!-- 由于未提供删除接口，暂时注释该功能 -->
      <!-- <el-button type="danger" plain @click="deleteBacthed()">批量删除</el-button> -->
    </div>

    <!-- 表格区域 -->
    <el-table :data="pageObj.parmData" class="customer-table" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="城市代码" prop="cityCode" width="120" align="center" show-overflow-tooltip />
      <el-table-column label="车辆类型" prop="vehicleType" width="120" align="center" show-overflow-tooltip />
      <el-table-column label="运价类型" prop="fareType" width="120" align="center" show-overflow-tooltip />
      <el-table-column label="起步价(元)" prop="startFare" width="110" align="center" />
      <el-table-column label="起步里程(km)" prop="startMile" width="120" align="center" />
      <el-table-column label="里程单价(元/km)" prop="unitPricePerMile" width="140" align="center" />
      <el-table-column label="时长单价(元/min)" prop="unitPricePerMinute" width="140" align="center" />
      <el-table-column label="版本号" prop="fareVersion" width="80" align="center" />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button size="small" :icon="Edit" circle type="primary" title="编辑"
                     @click="handleEdit(scope.$index, scope.row)"></el-button>
          <!-- 由于未提供删除接口，暂时注释该功能 -->
          <el-button size="small" :icon="Delete" circle type="danger" title="删除"
                     @click="handleDelete(scope.$index, scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <!-- 将分页属性绑定到 pageObj.page 的 current, size, total -->
      <el-pagination background layout="prev, pager, next, total" :total="pageObj.page.total"
                     :page-size="pageObj.page.size" :current-page="pageObj.page.current" @current-change="findData" />
    </div>

    <!-- 添加或修改计价规则对话框 -->
    <el-dialog v-model="pageObj.dialogObj.dialogFormVisible" draggable :title="pageObj.dialogObj.title"
               width="60%" class="customer-dialog">
      <el-form :model="pageObj.parm" label-position="right" label-width="140px" ref="priceRuleFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="ID" prop="id" v-if="pageObj.dialogObj.submitBtnTxt === '修  改'">
              <el-input v-model="pageObj.parm.id" placeholder="ID (系统生成)" disabled/>
            </el-form-item>
            <el-form-item label="城市代码" prop="cityCode">
              <el-input v-model="pageObj.parm.cityCode" placeholder="请输入城市代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="vehicleType">
              <el-input v-model="pageObj.parm.vehicleType" placeholder="请输入车辆类型"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="运价类型" prop="fareType">
              <el-input v-model="pageObj.parm.fareType" placeholder="请输入运价类型编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="版本号" prop="fareVersion">
              <el-input-number v-model="pageObj.parm.fareVersion" :min="1" placeholder="请输入版本号" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起步价 (元)" prop="startFare">
              <el-input-number v-model="pageObj.parm.startFare" :precision="2" :step="0.1" :min="0" placeholder="请输入起步价" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起步里程 (公里)" prop="startMile">
              <el-input-number v-model="pageObj.parm.startMile" :min="0" placeholder="请输入起步里程" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="里程单价 (元/公里)" prop="unitPricePerMile">
              <el-input-number v-model="pageObj.parm.unitPricePerMile" :precision="2" :step="0.1" :min="0" placeholder="请输入里程单价" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="时长单价 (元/分钟)" prop="unitPricePerMinute">
              <el-input-number v-model="pageObj.parm.unitPricePerMinute" :precision="2" :step="0.1" :min="0" placeholder="请输入时长单价" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
              <el-button @click="pageObj.dialogObj.dialogFormVisible = false">关 闭</el-button>
              <el-button type="primary" @click="addOrUpdateData()">{{ pageObj.dialogObj.submitBtnTxt }}</el-button>
          </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import axios from 'axios';
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Delete } from '@element-plus/icons-vue';

const priceRuleFormRef = ref(null);

const api = axios.create({
  baseURL: 'http://172.172.9.24:8090/api-boss',
  timeout: 5000
});

// reactive 状态对象
let pageObj = reactive({
  // 表格数据
  parmData: [],
  // 选中的行，用于批量操作
  parmIdsObj: [],
  // 分页和搜索条件, 结构与后端接口匹配
  page: {
    current: 1,
    size: 7,
    total: 0,
    priceRule: {
      cityCode: '',
      vehicleType: '',
    }
  },
  // 对话框相关数据
  dialogObj: {
    dialogFormVisible: false,
    title: '',
    submitBtnTxt: '',
  },
  // 对话框表单绑定的数据对象 (对应单个 PriceRule)
  parm: {
    id: null,
    cityCode: '',
    vehicleType: '',
    startFare: 0.0,
    startMile: 0,
    unitPricePerMile: 0.0,
    unitPricePerMinute: 0.0,
    fareVersion: 1,
    fareType: ''
  },
});

// 组件挂载后加载数据
onMounted(() => {
  findData();
});





// 处理删除操作
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    '确认删除该计价规则吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 调用删除接口
    console.log(row.id);
    const deleteUrl = `/price-rule/delete?id=${row.id}`;
    api.delete(deleteUrl).then(res => {
      console.log("删除响应:", res.data);
      // 根据 { "code": 1, "message": "..." } 格式处理响应
      if (res.data && res.data.code === 1) {
        ElMessage.success(res.data.message || "删除成功!");
        findData(pageObj.page.current); // 删除成功后刷新当前页数据
      } else {
        ElMessage.error(res.data.message || "删除失败!");
      }
    }).catch(err => {
      console.error("删除请求失败:", err);
      ElMessage.error("删除请求失败，请检查网络或联系管理员");
    });
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};













// 查询数据函数
const findData = (currentPage) => {
  if (currentPage) {
    pageObj.page.current = currentPage;
  }
  // 准备请求参数，匹配后端接口格式
  const params = {
    current: pageObj.page.current,
    size: pageObj.page.size,
    priceRule: {
      cityCode: pageObj.page.priceRule.cityCode || null,
      vehicleType: pageObj.page.priceRule.vehicleType || null,
    }
  };
  console.log("查询参数:", JSON.stringify(params));

  // 使用 POST 方法调用查询接口
  api.post("/price-rule/query", params).then(res => {
    console.log("查询结果:", res.data);
    // 假设后端返回 { code: 1, data: { records: [], total: 0, current: 1, size: 7 } }
    if (res.data && res.data.code === 1) {
      pageObj.parmData = res.data.data.records || [];
      pageObj.page.total = res.data.data.total || 0;
      pageObj.page.current = res.data.data.current || 1;
      pageObj.page.size = res.data.data.size || 7;
    } else {
      ElMessage.error(res.data.message || '数据加载失败');
      pageObj.parmData = [];
      pageObj.page.total = 0;
    }
  }).catch(error => {
    console.error("查询请求失败:", error);
    ElMessage.error("请求失败，请检查网络或联系管理员");
    pageObj.parmData = [];
    pageObj.page.total = 0;
  });
};

// 重置搜索表单
const resetForm = () => {
  pageObj.page.priceRule.cityCode = '';
  pageObj.page.priceRule.vehicleType = '';
  findData(1);
};

// 处理表格选中项变化
const handleSelectionChange = (rows) => {
  pageObj.parmIdsObj = rows;
};

// 显示新增对话框
const showDialog = () => {
  // 重置表单对象
  pageObj.parm = {
    id: null,
    cityCode: '',
    vehicleType: '',
    startFare: 10.0,
    startMile: 3,
    unitPricePerMile: 1.8,
    unitPricePerMinute: 0.5,
    fareVersion: 1,
    fareType: ''
  };
  pageObj.dialogObj.title = "新增计价规则";
  pageObj.dialogObj.submitBtnTxt = "添  加";
  pageObj.dialogObj.dialogFormVisible = true;
  priceRuleFormRef.value?.clearValidate();
};

// 显示编辑对话框
const handleEdit = (index, row) => {
  // 使用深拷贝，避免直接修改表格数据
  pageObj.parm = JSON.parse(JSON.stringify(row));
  pageObj.dialogObj.title = "修改计价规则";
  pageObj.dialogObj.submitBtnTxt = "修  改";
  pageObj.dialogObj.dialogFormVisible = true;
  priceRuleFormRef.value?.clearValidate();
};

// 处理新增或修改数据提交
const addOrUpdateData = () => {
  priceRuleFormRef.value?.validate((valid) => {
    if (valid) {
      const submitData = pageObj.parm;

      if (pageObj.dialogObj.submitBtnTxt === "添  加") {
        console.log("待添加的数据:", submitData);
        // 调用新增接口
        api.post("/price-rule/add", submitData).then(res => {
          // 根据 { "code": 1, "message": "..." } 格式处理响应
          if (res.data && res.data.code === 1) {
            ElMessage.success(res.data.message || "添加成功!");
            pageObj.dialogObj.dialogFormVisible = false;
            findData(1); // 成功后刷新第一页数据
          } else {
            ElMessage.error(res.data.message || "添加失败!");
          }
        }).catch(err => {
          console.error("添加请求失败:", err);
          ElMessage.error("添加请求失败，请检查网络或联系管理员");
        });
      } else { // 修改逻辑
        console.log("待修改的数据:", submitData);
        // 调用修改接口
        api.post("/price-rule/edit", submitData).then(res => {
          console.log("修改响应:", res.data);
          // 根据 { "code": 1, "message": "..." } 格式处理响应
          if (res.data && res.data.code === 1) {
            ElMessage.success(res.data.message || "修改成功!");
            pageObj.dialogObj.dialogFormVisible = false;
            findData(pageObj.page.current); // 修改成功后留在当前页
          } else {
            ElMessage.error(res.data.message || "修改失败!");
          }
        }).catch(err => {
          console.error("修改请求失败:", err);
          ElMessage.error("修改请求失败，请检查网络或联系管理员");
        });
      }
    } else {
      ElMessage.warning('请检查表单输入项！');
      return false;
    }
  });
};
</script>

<style>
/* 样式部分保持不变 */
.customer-page-container {
  padding: 15px;
  background-color: rgba(45, 55, 72, 0.65);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-radius: 8px;
  color: #cdd6e8;
  min-height: calc(100vh - 77px - 40px);
}

.search-form {
  background-color: rgba(31, 41, 55, 0.75);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  padding: 15px 15px 0 15px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.search-form .el-form-item__label {
  color: #d1d5db;
}
.search-form .el-input__wrapper {
  background-color: rgba(55, 65, 81, 0.8) !important;
  box-shadow: none !important;
  border: 1px solid rgba(75, 85, 99, 0.7);
}
.search-form .el-input__inner {
  color: #e5e7eb !important;
}
.search-form .el-input__inner::placeholder {
  color: #9ca3af;
}
.search-form .el-select .el-input__wrapper {
  background-color: rgba(55, 65, 81, 0.8) !important;
  border: 1px solid rgba(75, 85, 99, 0.7);
}
.search-form .el-select .el-input__inner {
  color: #e5e7eb !important;
}
.el-select-dropdown {
  background-color: #2d3748 !important;
  border: 1px solid #4b5563 !important;
}

.search-form .el-button--primary {
  background-color: #3b82f6;
  border-color: #3b82f6;
  color: #ffffff;
}
.search-form .el-button--primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}
.search-form .el-button {
  background-color: #4b5563;
  border-color: #4b5563;
  color: #e5e7eb;
}
.search-form .el-button:hover {
  background-color: #6b7280;
  border-color: #6b7280;
  color: #ffffff;
}

.action-buttons {
  margin-bottom: 15px;
}
.action-buttons .el-button--primary {
  background-color: #3b82f6;
  border-color: #3b82f6;
  color: #ffffff;
}
.action-buttons .el-button--primary:hover {
  background-color: #2563eb;
  border-color: #2563eb;
}
.action-buttons .el-button--danger.is-plain {
  color: #f87171;
  background-color: rgba(31, 41, 55, 0.75);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-color: #f87171;
  border-radius: 4px;
}
.action-buttons .el-button--danger.is-plain:hover {
  background: #ef4444;
  border-color: #ef4444;
  color: #ffffff;
  backdrop-filter: none;
  -webkit-backdrop-filter: none;
}

.customer-table {
  background-color: rgba(31, 41, 55, 0.7);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
  border: 1px solid rgba(75, 85, 99, 0.5);
  border-radius: 4px;
  overflow: hidden;
}

.customer-table .el-table__header-wrapper th {
  background-color: rgba(55, 65, 81, 0.75) !important;
  color: #e5e7eb !important;
  border-bottom: 1px solid rgba(75, 85, 99, 0.6) !important;
  padding: 10px 0 !important;
  vertical-align: middle;
  text-align: center;
}

.customer-table .el-table__row {
  background-color: transparent !important;
  color: #cdd6e8 !important;
}
.customer-table .el-table__row:hover > td {
  background-color: rgba(45, 55, 72, 0.5) !important;
  color: #ffffff !important;
}
.customer-table .el-table__row.el-table__row--striped {
  background-color: rgba(37, 48, 65, 0.3) !important;
}
.customer-table .el-table__row.el-table__row--striped:hover > td {
  background-color: rgba(45, 55, 72, 0.5) !important;
}

.customer-dialog .el-dialog {
  background-color: #2d3748;
  border-radius: 8px;
}

.el-table__fixed-right {
  background-color: rgba(31, 41, 55, 0.75);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
}
.el-table__fixed-right::before {
  background-color: transparent;
}
</style>
